package com.irdstudio.efp.edoc.service.impl.yed;


import com.irdstudio.efp.edoc.common.FileDataConstant;
import com.irdstudio.efp.edoc.common.UploadRtMsg;
import com.sunyard.client.bean.ClientBatchBean;
import com.sunyard.client.bean.ClientBatchFileBean;
import com.sunyard.client.bean.ClientBatchIndexBean;
import com.sunyard.client.bean.ClientFileBean;
import com.sunyard.client2.Client;
import com.sunyard.client2.FileAttrConstant;
import com.sunyard.ecm.server.bean.BatchBean;
import com.sunyard.ecm.server.bean.BatchFileBean;
import com.sunyard.ecm.server.bean.BatchIndexBean;
import com.sunyard.ecm.server.bean.FileBean;
import com.sunyard.util.OptionKey;
import com.sunyard.util.TransOptionKey;
import com.sunyard.ws.utils.XMLUtil;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 公共的文档上传操作
 *
 * @author xiaojunhui
 */
public class YedUploadFileUtils {

    private static Logger logger = LoggerFactory.getLogger(YedUploadFileUtils.class);

    static {
        if (!Client.isInit) {
            Client.init();
        }
    }
    /**
     * 追加文件
     *
     * @param yedNlsStamInfo
     * @param yedImgInfo
     * @param fileUrl
     * @param startDate   流水号生成日期
     * @param batch       批次号
     * @return
     */
    public static String addOneFile(YedNlsStamInfo yedNlsStamInfo, YedImgInfo yedImgInfo, String batchDate, String fileUrl, String startDate, String batch) throws Exception {
        ClientBatchBean clientBatchBean = getClientBatchBean(yedNlsStamInfo.getApplySeq(), batchDate);
        clientBatchBean.getIndex_Object().setContentID(batch);
        clientBatchBean.getIndex_Object().addCustomMap(FileDataConstant.STARTCOLUMN, startDate);

        ClientBatchFileBean batchFileBean = new ClientBatchFileBean();
        batchFileBean.setFilePartName(FileDataConstant.FILE_PART_NAME);
        // =========================添加文件=========================
        File path = new File(fileUrl);
        ClientFileBean fileBean = new ClientFileBean();
        // 操作类型为追加
        fileBean.setOptionType(OptionKey.U_ADD);

        fileBean.setFileName(path.getAbsolutePath());
        fileBean.setFileFormat(path.getName().substring(path.getName().lastIndexOf(".") + 1));
        fileBean.addOtherAtt(FileDataConstant.FILE_NATURE, yedImgInfo.getImgType());
        /** @date 2019/03/29 @author qiuyf  @describe 文件描述  */
        fileBean.addOtherAtt(FileAttrConstant.FILE_INFO, yedImgInfo.getImgType());
        // =========================设置索引对象信息开始=========================
        //流水号
        fileBean.addOtherAtt(FileAttrConstant.BUSI_SERIAL_NO, yedNlsStamInfo.getApplySeq());
        //流水号生成时间
        fileBean.addOtherAtt(FileAttrConstant.BUSI_START_DATE, startDate);
        //客户证件号码
        fileBean.addOtherAtt(FileAttrConstant.IDENTITY, yedNlsStamInfo.getCusCertCode());
        //客户名称
        fileBean.addOtherAtt(FileAttrConstant.CUSTOMER, yedNlsStamInfo.getCusName());
        //产品名称
        fileBean.addOtherAtt(FileAttrConstant.PRD_NAME, yedNlsStamInfo.getPrdName());
        // =========================设置索引对象信息结束=========================
        //查询当前批次的最大的页码
        int pageNum = getBusiFilePageNum(queryBatchInfo(batch, startDate));
        // 页码（上传批次中包含的第一个文件为页码1，第二个文件为页码2，如此类推...）
        fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_PAGENUM, String.valueOf(pageNum));
        // 目录树节点
        fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_TYPE, yedImgInfo.getTreeNodeId());
        // 扫描人（赋值登录用户名）
        fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_SCANUSER, Client.userName);
        // 文件中文名称
        fileBean.addOtherAtt(FileAttrConstant.FILE_CN_NAME, yedImgInfo.getImgCnName());
        // 图片的扫描参数（目前影像文件是读取存放在文件夹中的文件信息，不是扫描文件，所以填写空字符串）
        fileBean.addOtherAtt(FileAttrConstant.EXIF, "");
        batchFileBean.addFile(fileBean);
        clientBatchBean.addDocument_Object(batchFileBean);
        logger.info("#######更新追加一个批次的单个文件XML=========[" + XMLUtil.bean2XML(clientBatchBean) + "]#######");
        return Client.clientApi.update(clientBatchBean, null, true);

    }


    /**
     * 上传单个文件影像平台系统
     *
     * @param yedNlsStamInfo 申请记录封装信息
     * @param yedImgInfo  影像信息
     * @param fileUrl     文件的绝对路径
     * @param batchDate   批次时间
     * @param startDate   业务时间
     * @return String 影像平台返回的报文
     * @throws Exception 抛出的异常
     */
    public static String uploadOneFile(YedNlsStamInfo yedNlsStamInfo, YedImgInfo yedImgInfo, String fileUrl, String batchDate, String startDate) throws Exception {
        ClientBatchBean clientBatchBean = getClientBatchBean(yedNlsStamInfo.getApplySeq(), batchDate);
        ClientBatchIndexBean clientBatchIndexBean = new ClientBatchIndexBean();
        clientBatchIndexBean.addCustomMap(FileDataConstant.STARTCOLUMN, startDate);
        clientBatchIndexBean.addCustomMap(FileAttrConstant.BUSI_SERIAL_NO, yedNlsStamInfo.getApplySeq());
        //客户证件号
        clientBatchIndexBean.addCustomMap(FileAttrConstant.IDENTITY, yedNlsStamInfo.getCusCertCode());
        // 客户名
        clientBatchIndexBean.addCustomMap(FileAttrConstant.CUSTOMER, yedNlsStamInfo.getCusName());
        // 产品名
        clientBatchIndexBean.addCustomMap(FileAttrConstant.PRD_NAME, yedNlsStamInfo.getPrdName());
        // 上传文件个数
        clientBatchIndexBean.addCustomMap(FileAttrConstant.AMOUNT, "1");

        ClientBatchFileBean clientBatchFileBean = new ClientBatchFileBean();
        clientBatchFileBean.setFilePartName(FileDataConstant.FILE_PART_NAME);

        //获取文件地址
        ClientFileBean fileBean = new ClientFileBean();
        fileBean.setFileName(fileUrl);
        fileBean.setFileFormat(FilenameUtils.getExtension(fileUrl));
        //设置影像类型
        fileBean.addOtherAtt(FileDataConstant.FILE_NATURE, yedImgInfo.getImgType());
        // 页码（上传批次中包含的第一个文件为页码1，第二个文件为页码2，如此类推...）
        fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_PAGENUM, "1");
        // 目录树节点
        fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_TYPE, yedImgInfo.getTreeNodeId());
        // 扫描人（赋值登录用户名）
        fileBean.addOtherAtt(FileAttrConstant.BUSI_FILE_SCANUSER, Client.userName);
        // 文件中文名称
        fileBean.addOtherAtt(FileAttrConstant.FILE_CN_NAME, yedImgInfo.getImgCnName());
        // 图片的扫描参数（目前影像文件是读取存放在文件夹中的文件信息，不是扫描文件，所以填写空字符串）
        fileBean.addOtherAtt(FileAttrConstant.EXIF, "");
        clientBatchFileBean.addFile(fileBean);
        // 上传文件数
        clientBatchIndexBean.setAmount("1");
        clientBatchBean.setIndex_Object(clientBatchIndexBean);
        clientBatchBean.addDocument_Object(clientBatchFileBean);
        logger.info("上传一个文件到影像平台请求报文为：", XMLUtil.bean2XML(clientBatchBean));
        return Client.clientApi.upload(clientBatchBean, null);
    }

    /**
     * 登陆影像平台系统，并且获取clientbatchbean对象（通用抽取）
     *
     * @param applySeq
     * @param batchDate
     * @return
     */
    private static ClientBatchBean getClientBatchBean(String applySeq, String batchDate) {
        ClientBatchBean clientBatchBean = new ClientBatchBean();
        clientBatchBean.setModelCode(FileDataConstant.MODEL_CODE);
        clientBatchBean.setUser(Client.userName);
        clientBatchBean.setPassWord(Client.passWord);
        clientBatchBean.setOwnMD5(false);
        clientBatchBean.setBATCH_DATE(batchDate);
        clientBatchBean.setMACHINE_NUM(FileDataConstant.machineNum);
        clientBatchBean.setSERIAL_NUM(applySeq);
        clientBatchBean.setORGAN_NO(Client.organNo);
        return clientBatchBean;
    }

    /**
     * 解析影像系统返回的报文到对象
     *
     * @param retMsg
     * @return
     */
    public static UploadRtMsg explainRetMsg(String retMsg) {
        UploadRtMsg uploadRtMsg = new UploadRtMsg();
        uploadRtMsg.setMsg(retMsg);
        String[] msgArr = retMsg.split("<<::>>");
        if ("SUCCESS".equalsIgnoreCase(msgArr[0])) {
            //成功
            uploadRtMsg.setSuccess(true);
            if (msgArr.length > 1) {
                uploadRtMsg.setBatch(msgArr[1]);
            }
            if (msgArr.length > 2) {
                try {
                    uploadRtMsg.setRetCode(Integer.parseInt(msgArr[2]));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            uploadRtMsg.setSuccess(false);
            uploadRtMsg.setMsg(retMsg);
        }
        return uploadRtMsg;
    }

    public static String queryBatchInfo(String batch, String startDate) throws Exception {
        ClientBatchBean clientBatchBean = new ClientBatchBean();
        clientBatchBean.setModelCode(FileDataConstant.MODEL_CODE);
        clientBatchBean.setUser(Client.userName);
        clientBatchBean.setPassWord(Client.passWord);
        clientBatchBean.setDownLoad(true);
        clientBatchBean.getIndex_Object().setVersion("0");// 0为最新版本
        clientBatchBean.getIndex_Object().setContentID(batch);
        clientBatchBean.getIndex_Object().addCustomMap(FileDataConstant.STARTCOLUMN, startDate);
        ClientBatchFileBean documentObject = new ClientBatchFileBean();
        documentObject.setFilePartName(FileDataConstant.FILE_PART_NAME);
        clientBatchBean.addDocument_Object(documentObject);
        String str = XMLUtil.bean2XML(clientBatchBean);
        logger.info("#######查询批次XML=========[" + str + "]#######");
        return Client.clientApi.queryBatch(clientBatchBean, null);

    }

    public static Map<String, String> getUpdateBatchFileInfo(String resultMsg) {
        // 查询上传的产品信息
        if (Objects.nonNull(resultMsg) && !"".equals(resultMsg)) {
            String batchStr = resultMsg.split(TransOptionKey.SPLITSYM)[1];
            List<BatchBean> batchBeans = XMLUtil.xml2list(XMLUtil.removeHeadRoot(batchStr), BatchBean.class);
            for (BatchBean batchBean : batchBeans) {
                BatchIndexBean indexBeans = batchBean.getIndex_Object();
                return indexBeans.getCustomMap();
            }
        }
        return null;
    }

    public static int getBusiFilePageNum(String resultMsg) {
        // 页码
        if (Objects.nonNull(resultMsg) && !"".equals(resultMsg)) {
            String batchStr = resultMsg.split(TransOptionKey.SPLITSYM)[1];
            List<BatchBean> batchBeans = XMLUtil.xml2list(XMLUtil.removeHeadRoot(batchStr), BatchBean.class);
            for (BatchBean batchBean : batchBeans) {
                List<BatchFileBean> fileBeans = batchBean.getDocument_Objects();
                for (BatchFileBean batchFileBean : fileBeans) {
                    List<FileBean> files = batchFileBean.getFiles();
                    return files.size()+1;
                }
            }
        }
        return 1;
    }
}
